<template>
  <div>
    <textarea :id="id" ref="ckeditorRef"></textarea>
  </div>
</template>

<script>
export default {
  name: "ckeditor4",
  props: {
    value: '',
    ckeditorHeight: {
      default: 450
    }
  },
  watch: {
    // 监听prop的变化，更新ckeditor中的值
    value() {
      if (this.value !== this.ckeditor.getData()) {
        console.log(this.value)
        this.ckeditor.setData(this.value)
      }
    }
  },
  data() {
    return {
      id: parseInt(Math.random() * 10000).toString(),
      ckeditor: null
    }
  },
  mounted() {
    window.CKEDITOR_BASEPATH = '/ckeditor/'
    import('ckeditor/ckeditor.js').then(comp => {
      const self = this
      let imgUrl = '/compilation/compilation/uploadImage'
      //渲染编辑器
      self.ckeditor = CKEDITOR.replace(self.id, {
        height: this.ckeditorHeight,
        resize_enabled: false,
        toolbarGroups : [
          { name: 'clipboard', groups: [ 'clipboard', 'undo' ] },
          { name: 'editing', groups: [ 'find', 'selection', 'spellchecker', 'editing' ] },
          { name: 'links', groups: [ 'links' ] },
          { name: 'forms', groups: [ 'forms' ] },
          { name: 'tools', groups: [ 'tools' ] },
          { name: 'document', groups: [ 'mode', 'document', 'doctools' ] },
          { name: 'others', groups: [ 'others' ] },
          '/',
          { name: 'basicstyles', groups: [ 'basicstyles', 'cleanup' ] },
          { name: 'paragraph', groups: [ 'list', 'indent', 'blocks', 'align', 'bidi', 'paragraph' ] },
          { name: 'styles', groups: [ 'styles' ] },
          { name: 'colors', groups: [ 'colors' ] },
          { name: 'about', groups: [ 'about' ] }
        ],
        removeButtons: 'Underline,Subscript,Superscript,Anchor,Link,Unlink,Maximize,Source,About',
        removeDialogTabs: 'image:advanced;link:advanced',
        filebrowserImageUploadUrl: imgUrl,
        filebrowserUploadUrl: imgUrl,
        extraPlugins: 'uploadimage,preview',
        uploadUrl: imgUrl
      })

      // 设置初始内容
      self.ckeditor.setData(self.value)

      // 监听内容变更事件
      self.ckeditor.on("change", function() {
        self.$emit("input", self.ckeditor.getData())
      })

      self.ckeditor.on("instanceReady", function(evt) {
        self.$emit("ready", evt,CKEDITOR)
      })
    })
  },
  // 销毁组件前，销毁编辑器
  beforeDestroy() {
    // self.ckeditor.destroy()
  }
};
</script>